<template>
  <div class="processing-info">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>深加工信息管理</h2>
      <p class="page-description">管理深加工过程中的各项信息，包括食品安全、供应商信息和企业信息</p>
    </div>

    <!-- 深加工信息设置 -->
    <el-card class="info-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <h3>深加工信息</h3>
          <el-button type="primary" size="small" @click="openProcessingSettings">
            <el-icon>
              <Setting />
            </el-icon>
            设置
          </el-button>
        </div>
      </template>

      <!-- 深加工基本信息 -->
      <div class="processing-basic-info" :data="ProcessingData">
        <div class="info-grid">
          <div class="info-item">
            <label>班组</label>
            <span>{{ ProcessingData.team || '未设置' }}</span>
          </div>
          <div class="info-item">
            <label>负责人</label>
            <span>{{ ProcessingData.leader || '未设置' }}</span>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 食品安全信息 -->
    <el-card class="info-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <h3>食品安全信息</h3>
          <span class="upload-tip">支持多张图片上传</span>
        </div>
      </template>

      <div class="food-safety-uploads">
        <div class="uploaded-food-safety">
          <div v-for="(photo, idx) in foodSafetyPhotos" :key="photo.id" class="food-safety-item">
            <img v-if="photo.imagePath" :src="photo.imagePath" class="food-safety-img" />
            <el-icon class="img-delete-x" @click="deleteFoodSafetyPhoto(photo.id)">
              <Close />
            </el-icon>
          </div>
          <!-- 上传按钮，最多9张 -->
          <label v-if="foodSafetyPhotos.length < 10" class="food-safety-upload">
            <input type="file" accept="image/*" name="ImageFile" style="display: none"
              @change="handleFoodSafetyUpload" />
            <el-icon class="plus-icon">
              <Plus />
            </el-icon>
          </label>
        </div>
      </div>
    </el-card>

    <!-- 供应商信息 -->
    <el-card class="info-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <h3>供应商信息</h3>
        </div>
      </template>

      <!-- 原料 -->
      <div class="supplier-section">
        <div class="supplier-header">
          <h4>原料</h4>
          <el-button type="primary" size="small" @click="openRawMaterialSettings">设置</el-button>
        </div>
        <div class="supplier-info">
          <span>生产批次: {{ ProcessingData.batch || '未设置' }}</span>
        </div>
        <div class="supplier-materials">
          <h5>相关材料</h5>
          <div class="material-uploads">
            <div class="uploaded-materials">
              <div v-for="(photo, idx) in rawMaterialPhotos" :key="photo.id" class="material-item">
                <img v-if="photo.imagePath" :src="photo.imagePath" class="material-img" />
                <el-icon class="img-delete-x" @click="deleteRawMaterialPhoto(photo.id)">
                  <Close />
                </el-icon>
              </div>
              <!-- 上传按钮，最多9张 -->
              <label v-if="rawMaterialPhotos.length < 9" class="material-upload">
                <input type="file" accept="image/*" name="ImageFile" style="display: none"
                  @change="handleRawMaterialUpload" />
                <el-icon class="plus-icon">
                  <Plus />
                </el-icon>
              </label>
            </div>
          </div>
        </div>
      </div>

      <!-- 辅料 -->
      <div class="supplier-section">
        <div class="supplier-header">
          <h4>辅料</h4>
          <el-button type="primary" size="small" @click="openAuxiliaryMaterialSettings">设置</el-button>
        </div>
        <div class="supplier-info">
          <span>生产批次: {{ ProcessingData.batch || '未设置' }}</span>
        </div>
        <div class="supplier-materials">
          <h5>相关材料</h5>
          <div class="material-uploads">
            <div class="uploaded-materials">
              <div v-for="(photo, idx) in auxiliaryMaterialPhotos" :key="photo.id" class="material-item">
                <img v-if="photo.imagePath" :src="photo.imagePath" class="material-img" />
                <el-icon class="img-delete-x" @click="deleteAuxiliaryMaterialPhoto(photo.id)">
                  <Close />
                </el-icon>
              </div>
              <!-- 上传按钮，最多9张 -->
              <label v-if="auxiliaryMaterialPhotos.length < 10" class="material-upload">
                <input type="file" accept="image/*" name="ImageFile" style="display: none"
                  @change="handleAuxiliaryMaterialUpload" />
                <el-icon class="plus-icon">
                  <Plus />
                </el-icon>
              </label>
            </div>
          </div>
        </div>
      </div>

      <!-- 添加剂 -->
      <div class="supplier-section">
        <div class="supplier-header">
          <h4>添加剂</h4>
          <el-button type="primary" size="small" @click="openAdditiveSettings">设置</el-button>
        </div>
        <div class="supplier-info">
          <span>生产批次: {{ ProcessingData.batch || '未设置' }}</span>
        </div>
        <div class="supplier-materials">
          <h5>相关材料</h5>
          <div class="material-uploads">
            <div class="uploaded-materials">
              <div v-for="(photo, idx) in additivePhotos" :key="photo.id" class="material-item">
                <img v-if="photo.imagePath" :src="photo.imagePath" class="material-img" />
                <el-icon class="img-delete-x" @click="deleteAdditivePhoto(photo.id)">
                  <Close />
                </el-icon>
              </div>
              <!-- 上传按钮，最多9张 -->
              <label v-if="additivePhotos.length < 9" class="material-upload">
                <input type="file" accept="image/*" name="ImageFile" style="display: none"
                  @change="handleAdditiveUpload" />
                <el-icon class="plus-icon">
                  <Plus />
                </el-icon>
              </label>
            </div>
          </div>
        </div>
      </div>

      <!-- 包材 -->
      <div class="supplier-section">
        <div class="supplier-header">
          <h4>包材</h4>
          <el-button type="primary" size="small" @click="openPackagingMaterialSettings">设置</el-button>
        </div>
        <div class="supplier-info">
          <span>生产批次: {{ ProcessingData.batch || '未设置' }}</span>
        </div>
        <div class="supplier-materials">
          <h5>相关材料</h5>
          <div class="material-uploads">
            <div class="uploaded-materials">
              <div v-for="(photo, idx) in packagingMaterialPhotos" :key="photo.id" class="material-item">
                <img v-if="photo.imagePath" :src="photo.imagePath" class="material-img" />
                <el-icon class="img-delete-x" @click="deletePackagingMaterialPhoto(photo.id)">
                  <Close />
                </el-icon>
              </div>
              <!-- 上传按钮，最多9张 -->
              <label v-if="packagingMaterialPhotos.length < 9" class="material-upload">
                <input type="file" accept="image/*" name="ImageFile" style="display: none"
                  @change="handlePackagingMaterialUpload" />
                <el-icon class="plus-icon">
                  <Plus />
                </el-icon>
              </label>
            </div>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 企业信息 -->
    <el-card class="info-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <h3>企业信息</h3>
          <el-button type="primary" size="small" @click="openCompanySettings">
            <el-icon>
              <Setting />
            </el-icon>
            设置
          </el-button>
        </div>
      </template>

      <div class="company-details" :data="CompanyData">
        <div class="info-grid">
          <div class="info-item">
            <label>公司名称</label>
            <span>{{ CompanyData.companyName || '未设置' }}</span>
          </div>
          <div class="info-item">
            <label>生产许可证号</label>
            <span>{{ CompanyData.licenseNum || '未设置' }}</span>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 企业照片 -->
    <el-card class="info-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <h3>企业照片</h3>
          <span class="upload-tip">支持多张图片上传</span>
        </div>
      </template>

      <div class="company-photo-uploads">
        <div class="uploaded-company-photos">
          <div v-for="(photo, idx) in companyPhotos" :key="photo.id" class="company-photo-item">
            <img v-if="photo.imagePath" :src="photo.imagePath" class="company-photo-img" />
            <el-icon class="img-delete-x" @click="deleteCompanyPhoto(photo.id)">
              <Close />
            </el-icon>
          </div>
          <!-- 上传按钮，最多9张 -->
          <label v-if="companyPhotos.length < 10" class="company-photo-upload">
            <input type="file" accept="image/*" name="ImageFile" style="display: none"
              @change="handleCompanyPhotoUpload" />
            <el-icon class="plus-icon">
              <Plus />
            </el-icon>
          </label>
        </div>
      </div>
    </el-card>

    <!-- 深加工信息设置弹框 -->
    <el-dialog v-model="processingDialogVisible" title="深加工信息设置" width="600px">
      <el-form :model="processingForm" :rules="processingRules" ref="processingFormRef" label-width="120px">
        <el-form-item label="班组:" prop="team">
          <el-input v-model="processingForm.team" placeholder="请输入班组" />
        </el-form-item>
        <el-form-item label="负责人:" prop="leader">
          <el-input v-model="processingForm.leader" placeholder="请输入负责人" />
        </el-form-item>
        <el-form-item label="生产批次:">
          <el-input v-model="processingForm.batch" disabled placeholder="生产批次" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="processingDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveProcessingInfo">保存</el-button>
      </template>
    </el-dialog>

    <!-- 原料设置弹框 -->
    <el-dialog v-model="rawMaterialDialogVisible" title="原料设置" width="600px">
      <el-form :model="rawMaterialForm" label-width="120px">
        <el-form-item label="生产批次:">
          <el-input v-model="rawMaterialForm.batch" disabled placeholder="生产批次" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="rawMaterialDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveRawMaterialInfo">保存</el-button>
      </template>
    </el-dialog>

    <!-- 辅料设置弹框 -->
    <el-dialog v-model="auxiliaryMaterialDialogVisible" title="辅料设置" width="600px">
      <el-form :model="auxiliaryMaterialForm" label-width="120px">
        <el-form-item label="生产批次:">
          <el-input v-model="auxiliaryMaterialForm.batch" disabled placeholder="生产批次" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="auxiliaryMaterialDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveAuxiliaryMaterialInfo">保存</el-button>
      </template>
    </el-dialog>

    <!-- 添加剂设置弹框 -->
    <el-dialog v-model="additiveDialogVisible" title="添加剂设置" width="600px">
      <el-form :model="additiveForm" label-width="120px">
        <el-form-item label="生产批次:">
          <el-input v-model="additiveForm.batch" disabled placeholder="生产批次" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="additiveDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveAdditiveInfo">保存</el-button>
      </template>
    </el-dialog>

    <!-- 包材设置弹框 -->
    <el-dialog v-model="packagingMaterialDialogVisible" title="包材设置" width="600px">
      <el-form :model="packagingMaterialForm" label-width="120px">
        <el-form-item label="生产批次:">
          <el-input v-model="packagingMaterialForm.batch" disabled placeholder="生产批次" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="packagingMaterialDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="savePackagingMaterialInfo">保存</el-button>
      </template>
    </el-dialog>

    <!-- 企业信息设置弹框 -->
    <el-dialog v-model="companyDialogVisible" title="企业信息设置" width="600px">
      <el-form :model="companyForm" :rules="companyRules" ref="companyFormRef" label-width="120px">
        <el-form-item label="公司名称:" prop="companyName">
          <el-input v-model="companyForm.companyName" placeholder="请输入公司名称" />
        </el-form-item>
        <el-form-item label="生产许可证号:" prop="licenseNum">
          <el-input v-model="companyForm.licenseNum" placeholder="请输入生产许可证号" />
        </el-form-item>
        <el-form-item label="生产批次:">
          <el-input v-model="companyForm.batch" disabled placeholder="生产批次" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="companyDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveCompanyInfo">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { Plus, Close, Setting } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Traceability } from '@/Utils/Http'
import { useRoute } from 'vue-router'

const route = useRoute()


// 接口定义
interface PhotoItem {
  id: string
  imagePath?: string
  url?: string
}

// 深加工信息数据
const ProcessingData = ref<any>([])

// 企业信息数据
const CompanyData = ref<any>([])

// 食品安全信息数据
const foodSafetyPhotos = ref<PhotoItem[]>([])

// 原料相关材料数据
const rawMaterialPhotos = ref<PhotoItem[]>([])

// 辅料相关材料数据
const auxiliaryMaterialPhotos = ref<PhotoItem[]>([])

// 添加剂相关材料数据
const additivePhotos = ref<PhotoItem[]>([])

// 包材相关材料数据
const packagingMaterialPhotos = ref<PhotoItem[]>([])

// 企业照片数据
const companyPhotos = ref<PhotoItem[]>([])

// 弹框相关
const processingDialogVisible = ref(false)
const rawMaterialDialogVisible = ref(false)
const auxiliaryMaterialDialogVisible = ref(false)
const additiveDialogVisible = ref(false)
const packagingMaterialDialogVisible = ref(false)
const companyDialogVisible = ref(false)

// 表单引用
const processingFormRef = ref()
const companyFormRef = ref()

// 深加工信息表单
const processingForm = reactive({
  id: 0,
  team: '',
  leader: '',
  batch: route.query.batch as string || ''
})

// 原料表单
const rawMaterialForm = reactive({
  batch: route.query.batch as string || ''
})

// 辅料表单
const auxiliaryMaterialForm = reactive({
  batch: route.query.batch as string || ''
})

// 添加剂表单
const additiveForm = reactive({
  batch: route.query.batch as string || ''
})

// 包材表单
const packagingMaterialForm = reactive({
  batch: route.query.batch as string || ''
})

// 企业信息表单
const companyForm = reactive({
  id: 0,
  companyName: '',
  licenseNum: '',
  address: '',
  batch: route.query.batch as string || ''
})

// 深加工信息验证规则
const processingRules = {
  team: [
    { required: true, message: '请输入班组', trigger: 'blur' }
  ],
  leader: [
    { required: true, message: '请输入负责人', trigger: 'blur' }
  ]
}

// 企业信息验证规则
const companyRules = {
  companyName: [
    { required: true, message: '请输入公司名称', trigger: 'blur' }
  ],
  licenseNum: [
    { required: true, message: '请输入生产许可证号', trigger: 'blur' }
  ],
}

// 获取深加工信息
const getProcessingInfo = () => {
  Traceability.get('/Deeprocessing/GetDeeprocessingModel', {
    params: { Batch: route.query.batch }
  }).then(res => {
    if (res.data.code == 200) {
      ProcessingData.value = res.data.data
      // 反填表单数据
      if (ProcessingData.value && Object.keys(ProcessingData.value).length > 0) {
        processingForm.id = ProcessingData.value.id || 0
        processingForm.team = ProcessingData.value.team || ''
        processingForm.leader = ProcessingData.value.leader || ''
        processingForm.batch = route.query.batch as string || '' // 始终使用路由参数
      }
    }
  }).catch(error => {
    console.error('获取深加工信息失败:', error)
    // 如果获取失败，使用默认值
    ProcessingData.value = {
      team: '',
      leader: '',
      batch: route.query.batch || ''
    }
    processingForm.batch = (route.query.batch as string) || ''
  })
}

// 获取企业信息
const getCompanyInfo = () => {
  Traceability.get('/Deeprocessing/GetDeepProcessingCompanyQuery', {
    params: { Batch: route.query.batch }
  }).then(res => {
    if (res.data.code == 200) {
      CompanyData.value = res.data.data
      // 反填表单数据
      if (CompanyData.value && Object.keys(CompanyData.value).length > 0) {
        companyForm.id = CompanyData.value.id || 0
        companyForm.companyName = CompanyData.value.companyName || ''
        companyForm.licenseNum = CompanyData.value.licenseNum || ''
        companyForm.batch = route.query.batch as string || '' // 始终使用路由参数
      }
    }
  }).catch(error => {
    console.error('获取企业信息失败:', error)
    // 如果获取失败，使用默认值
    CompanyData.value = {
      companyName: '',
      license: '',
      address: '',
      batch: route.query.batch || ''
    }
    companyForm.batch = (route.query.batch as string) || ''
  })
}

// 获取食品安全图片
const fetchFoodSafetyImages = async () => {
  try {
    const batch = route.query.batch as string
    const res = await Traceability.get('/UploadBatchImage/GetBatchImagesQuery', {
      params: { ImageType: 6, BatchNo: batch }
    })

    foodSafetyPhotos.value = Array.isArray(res.data.data)
      ? res.data.data.filter((item: any) => !!item && !!item.imagePath)
      : []
  } catch (error) {
    console.error('获取食品安全图片失败:', error)
  }
}

// 获取原料相关材料图片
const fetchRawMaterialImages = async () => {
  try {
    const batch = route.query.batch as string
    const res = await Traceability.get('/UploadBatchImage/GetBatchImagesQuery', {
      params: { ImageType: 7, BatchNo: batch }
    })

    rawMaterialPhotos.value = Array.isArray(res.data.data)
      ? res.data.data.filter((item: any) => !!item && !!item.imagePath)
      : []
  } catch (error) {
    console.error('获取原料相关材料图片失败:', error)
  }
}

// 获取辅料相关材料图片
const fetchAuxiliaryMaterialImages = async () => {
  try {
    const batch = route.query.batch as string
    const res = await Traceability.get('/UploadBatchImage/GetBatchImagesQuery', {
      params: { ImageType: 8, BatchNo: batch }
    })

    auxiliaryMaterialPhotos.value = Array.isArray(res.data.data)
      ? res.data.data.filter((item: any) => !!item && !!item.imagePath)
      : []
  } catch (error) {
    console.error('获取辅料相关材料图片失败:', error)
  }
}

// 获取添加剂相关材料图片
const fetchAdditiveImages = async () => {
  try {
    const batch = route.query.batch as string
    const res = await Traceability.get('/UploadBatchImage/GetBatchImagesQuery', {
      params: { ImageType: 9, BatchNo: batch }
    })

    additivePhotos.value = Array.isArray(res.data.data)
      ? res.data.data.filter((item: any) => !!item && !!item.imagePath)
      : []
  } catch (error) {
    console.error('获取添加剂相关材料图片失败:', error)
  }
}

// 获取包材相关材料图片
const fetchPackagingMaterialImages = async () => {
  try {
    const batch = route.query.batch as string
    const res = await Traceability.get('/UploadBatchImage/GetBatchImagesQuery', {
      params: { ImageType: 10, BatchNo: batch }
    })

    packagingMaterialPhotos.value = Array.isArray(res.data.data)
      ? res.data.data.filter((item: any) => !!item && !!item.imagePath)
      : []
  } catch (error) {
    console.error('获取包材相关材料图片失败:', error)
  }
}

// 获取企业照片
const fetchCompanyPhotoImages = async () => {
  try {
    const batch = route.query.batch as string
    const res = await Traceability.get('/UploadBatchImage/GetBatchImagesQuery', {
      params: { ImageType: 11, BatchNo: batch }
    })

    companyPhotos.value = Array.isArray(res.data.data)
      ? res.data.data.filter((item: any) => !!item && !!item.imagePath)
      : []
  } catch (error) {
    console.error('获取企业照片失败:', error)
  }
}

// 通用上传函数
const handleImageUpload = async (event: Event, imageType: string, targetArray: any[], fetchFunction: () => Promise<void>) => {
  const files = (event.target as HTMLInputElement).files
  if (!files || !files.length) return

  if (targetArray.length + files.length > 9) {
    ElMessage.warning('最多只能上传9张图片')
    return
  }

  const formData = new FormData()
  formData.append('ImageFile', files[0])
  formData.append('BatchNo', route.query.batch as string)
  formData.append('ImageType', imageType)

  try {
    const res = await Traceability.post('/UploadBatchImage/UploadBatch', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })

    if (res.data && res.data.code === 300) {
      ElMessage.success('上传成功')
      await fetchFunction()
    } else {
      ElMessage.error(res.data?.message || '上传失败')
    }
  } catch (error) {
    console.error('上传图片失败:', error)
    ElMessage.error('上传失败')
  }

  ; (event.target as HTMLInputElement).value = ''
}

// 通用删除函数
const deleteImage = async (id: string, imageType: string, fetchFunction: () => Promise<void>) => {
  try {
    await ElMessageBox.confirm('确定删除图片么?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const res = await Traceability.delete('/UploadBatchImage/DelBatchImage', {
      params: {
        Id: id,
        ImageType: imageType
      }
    })

    if (res.data && res.data.code === 500) {
      ElMessage.success('删除成功')
      await fetchFunction()
    } else {
      ElMessage.error(res.data?.message || '删除失败')
    }
  } catch (error) {
    if (error === 'cancel') {
      return
    }
    console.error('删除图片失败:', error)
    ElMessage.error('删除失败')
  }
}

// 食品安全相关函数
const handleFoodSafetyUpload = (event: Event) => {
  handleImageUpload(event, '6', foodSafetyPhotos.value, fetchFoodSafetyImages)
}

const deleteFoodSafetyPhoto = (id: string) => {
  deleteImage(id, '6', fetchFoodSafetyImages)
}

// 原料相关函数
const handleRawMaterialUpload = (event: Event) => {
  handleImageUpload(event, '7', rawMaterialPhotos.value, fetchRawMaterialImages)
}

const deleteRawMaterialPhoto = (id: string) => {
  deleteImage(id, '7', fetchRawMaterialImages)
}

// 辅料相关函数
const handleAuxiliaryMaterialUpload = (event: Event) => {
  handleImageUpload(event, '8', auxiliaryMaterialPhotos.value, fetchAuxiliaryMaterialImages)
}

const deleteAuxiliaryMaterialPhoto = (id: string) => {
  deleteImage(id, '8', fetchAuxiliaryMaterialImages)
}

// 添加剂相关函数
const handleAdditiveUpload = (event: Event) => {
  handleImageUpload(event, '9', additivePhotos.value, fetchAdditiveImages)
}

const deleteAdditivePhoto = (id: string) => {
  deleteImage(id, '9', fetchAdditiveImages)
}

// 包材相关函数
const handlePackagingMaterialUpload = (event: Event) => {
  handleImageUpload(event, '10', packagingMaterialPhotos.value, fetchPackagingMaterialImages)
}

const deletePackagingMaterialPhoto = (id: string) => {
  deleteImage(id, '10', fetchPackagingMaterialImages)
}

// 企业照片相关函数
const handleCompanyPhotoUpload = (event: Event) => {
  handleImageUpload(event, '11', companyPhotos.value, fetchCompanyPhotoImages)
}

const deleteCompanyPhoto = (id: string) => {
  deleteImage(id, '11', fetchCompanyPhotoImages)
}

// 打开设置弹框函数
const openProcessingSettings = () => {
  // 反填现有数据
  if (ProcessingData.value && Object.keys(ProcessingData.value).length > 0) {
    processingForm.id = ProcessingData.value.id || 0
    processingForm.team = ProcessingData.value.team || ''
    processingForm.leader = ProcessingData.value.leader || ''
    processingForm.batch = route.query.batch as string || '' // 始终使用路由参数
  }
  processingDialogVisible.value = true
}

const openRawMaterialSettings = () => {
  rawMaterialDialogVisible.value = true
}

const openAuxiliaryMaterialSettings = () => {
  auxiliaryMaterialDialogVisible.value = true
}

const openAdditiveSettings = () => {
  additiveDialogVisible.value = true
}

const openPackagingMaterialSettings = () => {
  packagingMaterialDialogVisible.value = true
}

const openCompanySettings = () => {
  // 反填现有数据
  if (CompanyData.value && Object.keys(CompanyData.value).length > 0) {
    companyForm.id = CompanyData.value.id || 0
    companyForm.companyName = CompanyData.value.companyName || ''
    companyForm.licenseNum = CompanyData.value.licenseNum || ''
    companyForm.batch = route.query.batch as string || '' // 始终使用路由参数
  }
  companyDialogVisible.value = true
}

// 保存函数
const saveProcessingInfo = async () => {
  // 表单验证
  if (!processingFormRef.value) return
  
  try {
    await processingFormRef.value.validate()
    
    console.log('保存深加工信息:', processingForm)
    
    // 调用深加工信息添加接口
    Traceability.post('/Deeprocessing/AddDeeprocessing', processingForm).then(res => {
      if (res.data.code == 300) {
        ElMessage.success('深加工信息保存成功')
        getProcessingInfo()
        processingDialogVisible.value = false
      } else {
        ElMessage.error(res.data.message || '深加工信息保存失败')
      }
    }).catch(error => {
      console.error('保存深加工信息失败:', error)
      ElMessage.error('保存深加工信息失败')
    })
  } catch (error) {
    console.log('表单验证失败:', error)
  }
}

const saveRawMaterialInfo = () => {
  console.log('保存原料信息:', rawMaterialForm)
  ElMessage.success('原料信息保存成功')
  rawMaterialDialogVisible.value = false
}

const saveAuxiliaryMaterialInfo = () => {
  console.log('保存辅料信息:', auxiliaryMaterialForm)
  ElMessage.success('辅料信息保存成功')
  auxiliaryMaterialDialogVisible.value = false
}

const saveAdditiveInfo = () => {
  console.log('保存添加剂信息:', additiveForm)
  ElMessage.success('添加剂信息保存成功')
  additiveDialogVisible.value = false
}

const savePackagingMaterialInfo = () => {
  console.log('保存包材信息:', packagingMaterialForm)
  ElMessage.success('包材信息保存成功')
  packagingMaterialDialogVisible.value = false
}

const saveCompanyInfo = async () => {
  // 表单验证
  if (!companyFormRef.value) return
  
  try {
    await companyFormRef.value.validate()
    
    console.log('保存企业信息:', companyForm)
    
    // 调用企业信息添加接口
    Traceability.post('/Deeprocessing/AddDeepProcessingCompany', companyForm).then(res => {
      if (res.data.code == 300) {
        ElMessage.success('企业信息保存成功')
        getCompanyInfo()
        companyDialogVisible.value = false
      } else {
        ElMessage.error(res.data.message || '企业信息保存失败')
      }
    }).catch(error => {
      console.error('保存企业信息失败:', error)
      ElMessage.error('保存企业信息失败')
    })
  } catch (error) {
    console.log('表单验证失败:', error)
  }
}

onMounted(() => {
  getProcessingInfo()
  getCompanyInfo()
  fetchFoodSafetyImages()
  fetchRawMaterialImages()
  fetchAuxiliaryMaterialImages()
  fetchAdditiveImages()
  fetchPackagingMaterialImages()
  fetchCompanyPhotoImages()
})
</script>

<style scoped>
.processing-info {
  padding: 16px;
  background: #f5f7fa;
  min-height: 100vh;
}

/* 页面标题 */
.page-header {
  margin-bottom: 16px;
  text-align: center;
}

.page-header h2 {
  margin: 0 0 6px 0;
  color: #2c3e50;
  font-size: 24px;
  font-weight: 600;
}

.page-description {
  margin: 0;
  color: #7f8c8d;
  font-size: 13px;
}

/* 卡片样式 */
.info-card {
  margin-bottom: 16px;
  border-radius: 8px;
  border: none;
  box-shadow: 0 2px 8px 0 rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.info-card:hover {
  box-shadow: 0 4px 20px 0 rgba(0, 0, 0, 0.15);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0;
}

.card-header h3 {
  margin: 0;
  color: #2c3e50;
  font-size: 16px;
  font-weight: 600;
}

.upload-tip {
  color: #909399;
  font-size: 11px;
  background: #f0f9ff;
  padding: 3px 6px;
  border-radius: 3px;
  border: 1px solid #b3d8ff;
}

/* 信息网格布局 */
.info-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
  gap: 12px;
  padding: 12px 0;
}

.info-item {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.info-item label {
  color: #606266;
  font-size: 12px;
  font-weight: 500;
}

.info-item span {
  color: #2c3e50;
  font-size: 14px;
  font-weight: 400;
  padding: 6px 10px;
  background: #f8f9fa;
  border-radius: 4px;
  border-left: 3px solid #409eff;
}

/* 供应商信息样式 */
.supplier-section {
  margin-bottom: 20px;
  padding: 15px;
  border: 1px solid #e9ecef;
  border-radius: 8px;
  background: #fafafa;
}

.supplier-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.supplier-header h4 {
  margin: 0;
  color: #2c3e50;
  font-size: 14px;
  font-weight: 600;
}

.supplier-info {
  margin-bottom: 15px;
  color: #666;
  font-size: 13px;
}

.supplier-materials h5 {
  margin: 0 0 10px 0;
  color: #2c3e50;
  font-size: 13px;
  font-weight: 500;
}

/* 图片上传区域 */
.food-safety-uploads,
.material-uploads,
.company-photo-uploads {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  align-items: flex-start;
}

.uploaded-food-safety,
.uploaded-materials,
.uploaded-company-photos {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}

.food-safety-item,
.material-item,
.company-photo-item {
  position: relative;
  width: 100px;
  height: 100px;
  border: 2px solid #e9ecef;
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s ease;
  cursor: pointer;
}

.food-safety-item:hover,
.material-item:hover,
.company-photo-item:hover {
  border-color: #409eff;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
}

.food-safety-img,
.material-img,
.company-photo-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 6px;
}

.img-delete-x {
  position: absolute;
  top: 4px;
  right: 4px;
  color: white;
  font-size: 16px;
  cursor: pointer;
  padding: 4px;
  border-radius: 50%;
  background: rgba(255, 0, 0, 0.7);
  transition: all 0.3s ease;
  z-index: 10;
}

.img-delete-x:hover {
  background: rgba(255, 0, 0, 0.9);
  transform: scale(1.1);
}

.food-safety-upload,
.material-upload,
.company-photo-upload {
  position: relative;
  width: 100px;
  height: 100px;
  border: 2px dashed #d9d9d9;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s ease;
  background: #fafafa;
}

.food-safety-upload:hover,
.material-upload:hover,
.company-photo-upload:hover {
  border-color: #409eff;
  background: #f0f9ff;
}

.plus-icon {
  font-size: 24px;
  color: #999;
  transition: color 0.3s ease;
}

.food-safety-upload:hover .plus-icon,
.material-upload:hover .plus-icon,
.company-photo-upload:hover .plus-icon {
  color: #409eff;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .processing-info {
    padding: 12px;
  }

  .info-grid {
    grid-template-columns: 1fr;
    gap: 8px;
  }

  .food-safety-item,
  .material-item,
  .company-photo-item,
  .food-safety-upload,
  .material-upload,
  .company-photo-upload {
    width: 80px;
    height: 80px;
  }

  .plus-icon {
    font-size: 20px;
  }
}

/* 按钮样式优化 */
.el-button {
  border-radius: 8px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.el-button--primary {
  background: linear-gradient(135deg, #409eff 0%, #5a9eff 100%);
  border: none;
}

.el-button--primary:hover {
  background: linear-gradient(135deg, #5a9eff 0%, #409eff 100%);
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.4);
}

/* 对话框样式优化 */
:deep(.el-dialog) {
  border-radius: 8px;
}

:deep(.el-dialog__header) {
  background: #f8f9fa;
  border-radius: 8px 8px 0 0;
  padding: 16px 20px;
  border-bottom: 1px solid #e9ecef;
}

:deep(.el-dialog__title) {
  color: #2c3e50;
  font-weight: 600;
  font-size: 16px;
}

:deep(.el-dialog__body) {
  padding: 20px;
}

:deep(.el-dialog__footer) {
  padding: 12px 20px 20px;
  border-top: 1px solid #e9ecef;
}
</style>
